package com.rongxing.config;

import com.github.pagehelper.PageInterceptor;
import com.github.pagehelper.util.StringUtil;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Intercepts(
        {
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        }
)
public class MyPageInterceptor extends PageInterceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        var rs = super.intercept(invocation);
        if(rs instanceof List<?> rsList && rsList.size()>=1 && rsList.get(0) instanceof Map){
            var rsListMap = (List<Map>) rsList;
            var sb = new StringBuilder();
            for (int i = 0; i < rsList.size(); i++) {
                var map = (Map) rsList.get(i);
                Map mapNew = new HashMap((int)Math.ceil(map.size()/0.75));
                for (Object o : map.entrySet()) {
                    var e = (Map.Entry) o;
                    mapNew.put(underlineToCamel((String) e.getKey(),sb),e.getValue());
                }
                rsListMap.set(i,mapNew);
            }
        }
        return rs;
    }

    /**下划线转小驼峰*/
    public static String underlineToCamel(String key,StringBuilder sb) {
        if (StringUtil.isEmpty(key)) {
            return "";
        }
        int len = key.length();
        if(sb==null)sb = new StringBuilder(len);
        else sb.setLength(0);
        for (int i = 0; i < len; i++) {
            char c = Character.toLowerCase(key.charAt(i));
            if (c == '_') {
                if (++i < len) {
                    sb.append(Character.toUpperCase(key.charAt(i)));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}